package com.jinyi.wwdeng.autodialer.utils

import android.content.Context
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.TelephonyCallback
import android.telephony.TelephonyManager
import androidx.annotation.RequiresApi

/**
 * 通话状态工具类监听
 */
class CallStateHelper(private val context: Context)  {
    private val telephonyManager: TelephonyManager by lazy {
        context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    }

    private var phoneStateListener: PhoneStateListener? = null
    private var telephonyCallback: Any? = null
    private var callStateListener: CallStateListener? = null

    /**
     * 通话状态监听接口
     */
    interface CallStateListener {
        fun onCallStateIdle() // 通话空闲/挂断
        fun onCallStateRinging() // 来电响铃
        fun onCallStateOffHook() // 通话中
    }

    /**
     * 开始监听通话状态
     */
    fun startListening(listener: CallStateListener) {
        this.callStateListener = listener

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            startModernListening()
        } else {
            startLegacyListening()
        }
    }

    /**
     * 停止监听通话状态
     */
    fun stopListening() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            stopModernListening()
        } else {
            stopLegacyListening()
        }
        callStateListener = null
    }

    /**
     * Android 12+ 使用新的 TelephonyCallback
     */
    @RequiresApi(Build.VERSION_CODES.S)
    private fun startModernListening() {
        val callback = object : TelephonyCallback(), TelephonyCallback.CallStateListener {
            override fun onCallStateChanged(state: Int) {
                handleCallState(state)
            }
        }

        telephonyManager.registerTelephonyCallback(
            context.mainExecutor,
            callback
        )
        telephonyCallback = callback
    }

    /**
     * Android 11及以下使用传统的 PhoneStateListener
     */
    @Suppress("DEPRECATION")
    private fun startLegacyListening() {
        phoneStateListener = object : PhoneStateListener() {
            override fun onCallStateChanged(state: Int, phoneNumber: String?) {
                handleCallState(state)
            }
        }
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
    }

    /**
     * 停止现代版本监听
     */
    @RequiresApi(Build.VERSION_CODES.S)
    private fun stopModernListening() {
        (telephonyCallback as? TelephonyCallback)?.let {
            telephonyManager.unregisterTelephonyCallback(it)
        }
        telephonyCallback = null
    }

    /**
     * 停止传统版本监听
     */
    @Suppress("DEPRECATION")
    private fun stopLegacyListening() {
        phoneStateListener?.let {
            telephonyManager.listen(it, PhoneStateListener.LISTEN_NONE)
        }
        phoneStateListener = null
    }

    /**
     * 处理通话状态变化
     */
    private fun handleCallState(state: Int) {
        when (state) {
            TelephonyManager.CALL_STATE_IDLE -> {
                callStateListener?.onCallStateIdle()
            }
            TelephonyManager.CALL_STATE_RINGING -> {
                callStateListener?.onCallStateRinging()
            }
            TelephonyManager.CALL_STATE_OFFHOOK -> {
                callStateListener?.onCallStateOffHook()
            }
        }
    }

    /**
     * 获取当前通话状态（兼容方法）
     */
    fun getCurrentCallState(): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+ 可能需要额外权限处理
            telephonyManager.callState
        } else {
            @Suppress("DEPRECATION")
            telephonyManager.callState
        }
    }

    /**
     * 检查是否正在通话中
     */
    fun isInCall(): Boolean {
        val state = getCurrentCallState()
        return state == TelephonyManager.CALL_STATE_OFFHOOK
    }

    /**
     * 检查是否有来电
     */
    fun isRinging(): Boolean {
        val state = getCurrentCallState()
        return state == TelephonyManager.CALL_STATE_RINGING
    }

    /**
     * 清理资源
     */
    fun release() {
        stopListening()
    }
}